const userObj = require('../modules/User');
const fs = require('fs');
const path = require('path');

let UserController = {
    get_index: function (req, res) {
        res.send('ok');
    },

    //用户登录验证
    post_login: async function (req, res) {
        let data = req.body;
        let resultDate = await userObj.checkLogin(data);
        res.send(resultDate);
    },

    //用户注册验证
    post_logup: async function (req, res) {
        let data = req.body;
        let resultDate = await userObj.checkLogup(data);
        res.send(resultDate);
    },

    //用户修改头像
    post_userImg: async function (req, res) {
        const files = req.files
        const user = JSON.parse(req.body.userData)
        let is = fs.createReadStream(files.file.path);
        const filePath = path.resolve(__dirname,'../../../public/images/' + files.file.originalFilename);
        let os = fs.createWriteStream(filePath);
        is.pipe(os);
        is.on('end', function () {
            fs.unlinkSync(files.file.path);
        });
        let resultDate = await userObj.saveImg({
            'filesName': files.file.originalFilename,
            'uid': user.user_detail_id,
        });
        res.send(resultDate);
    },

    get_img: async function (req, res) {
        let data = req.query
        console.log(data);
        const filePath = path.resolve(__dirname, `../../../public/images/${data.url}`);
        // 给客户端返回一个文件流 type类型
        res.set('content-type', { "png": "image/png", "jpg": "image/jpeg" });//设置返回类型
        var stream = fs.createReadStream(filePath);
        var responseData = [];//存储文件流
        if (stream) {//判断状态
            stream.on('data', function (chunk) {
                responseData.push(chunk);
            });
            stream.on('end', function () {
                var finalData = Buffer.concat(responseData);
                res.write(finalData);
                res.end();
            });
        }
    },
    //用户修改信息
    post_userMsg: async function (req, res) {
        let data = req.body;
        let resultDate = await userObj.updateMsg(data);
        res.send(resultDate);
    }
}
module.exports = UserController;